package org.thinkinbunny.financial.activity;

import java.io.File;

import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.service.DownloadService;
import org.thinkinbunny.financial.updateManger.DownloadListener;
import org.thinkinbunny.financial.util.ApkUtil;
import org.thinkinbunny.financial.util.ShowTools;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateActivity extends MyActivity implements OnClickListener {

	private TextView progress;
	private ProgressBar progressBar;
	private final Handler handler = new UIHandler();
	private DownloadService servcie;
	// private Button downButton;
	private Button pauseButton;
	String url, version;
	boolean isDownFinish = false;

	private final class UIHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				int downloaded_size = msg.getData().getInt("size");
				progressBar.setProgress(downloaded_size);
				int result = (int) ((float) downloaded_size
						/ progressBar.getMax() * 100);
				progress.setText(result + "%");
				if (progressBar.getMax() == progressBar.getProgress()) {
					Toast.makeText(getApplicationContext(),
							getString(R.string.downFileok), Toast.LENGTH_LONG)
							.show();
					isDownFinish = true;
					pauseButton.setText(getString(R.string.install));
					File updateFile = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/JdFinancial/DroidAccount_" + version + ".apk");
					ApkUtil.ApkInstall(UpdateActivity.this,
							updateFile.getAbsolutePath());
					;

				}
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_update);
		setTitle(getString(R.string.checkupdate));
		url = getIntent().getStringExtra("url");
		version = getIntent().getStringExtra("version");
		// path = (EditText) this.findViewById(R.id.editText);
		progress = (TextView) findViewById(R.id.textView);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		// downButton = (Button) findViewById(R.id.downButton);
		pauseButton = (Button) findViewById(R.id.pauseButton);
		// downButton.setOnClickListener(new DownloadButton());
		pauseButton.setOnClickListener(this);
		Down();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		finish();
		super.onStop();
	}

	@Override
	protected void onResume() {

		// TODO Auto-generated method stub
		super.onResume();
	}

	void Down() {
		DownloadTask task;
		try {
			task = new DownloadTask(url);
			servcie.isPause = false;
			// v.setEnabled(false);
			pauseButton.setEnabled(true);
			new Thread(task).start();
			ShowTools.toastInThread(getString(R.string.downFileing));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// private final class DownloadButton implements View.OnClickListener {
	// @Override
	// public void onClick(View v) {
	// DownloadTask task;
	// try {
	// task = new DownloadTask(url);
	// servcie.isPause = false;
	// v.setEnabled(false);
	// pauseButton.setEnabled(true);
	// new Thread(task).start();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.pauseButton) {

			if (servcie.isPause) {
				Down();
				((Button) v).setText(getString(R.string.downpause));
			} else {
				servcie.isPause = true;
				((Button) v).setText(getString(R.string.downcontinue));
				// v.setEnabled(false);
			}
			if (isDownFinish) {
				File updateFile = new File(Environment
						.getExternalStorageDirectory().getAbsolutePath()
						+ "/JdFinancial/JdFinancial.apk");
				ApkUtil.ApkInstall(UpdateActivity.this,
						updateFile.getAbsolutePath());
				;

			}

			// downButton.setEnabled(true);

		}
		super.onClick(v);
	}

	public class PauseButton implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (servcie.isPause) {
				Down();
			} else {
				servcie.isPause = true;
				// v.setEnabled(false);
			}

			// downButton.setEnabled(true);
		}
	}

	private final class DownloadTask implements Runnable {

		public DownloadTask(String target) {
			try {
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// Environment.getExternalStorageDirectory();
					File destination = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/JdFinancial");

					servcie = new DownloadService(target, destination, 1,
							getApplicationContext());

					progressBar.setMax(servcie.fileSize);
				} else {
					Toast.makeText(getApplicationContext(),
							getString(R.string.checkSdCard), Toast.LENGTH_LONG)
							.show();
				}
			} catch (Exception e) {
				// TODO: handle exception
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				startActivity(intent);
				ShowTools.toastInThread(getString(R.string.systemException));
			}

		}

		@Override
		public void run() {
			try {
				servcie.download(new DownloadListener() {

					@Override
					public void onDownload(int downloaded_size) {
						Message message = new Message();
						message.what = 1;
						message.getData().putInt("size", downloaded_size);
						handler.sendMessage(message);
					}

				});
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}
